//
//  MoreViewController.m
//  shise
//
//  Created by 徐国庆 on 14/12/17.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "MoreViewController.h"
#import "MoreCell.h"
#import "MoreDetailViewController.h"
#import "NetHandler.h"
#import "Food.h"
#import "UIImageView+WebCache.h"
#import "CrossSlipViewController.h"
#import "ViewController.h"
#import "AllFoodMenuViewController.h"
#import "Reachability.h"
#import "MBProgressHUD.h"

@interface MoreViewController ()<UITableViewDelegate, UITableViewDataSource>

// 定义可变数组装把数据处理成对象后存入数组中
@property(nonatomic, retain)NSMutableArray *array;
// 把tableView定义成属性
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)MBProgressHUD *noHUD;

@end

@implementation MoreViewController

// 数组初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.array = [NSMutableArray array];
        [self handleData];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
}

// 设置cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

// 设置每个cell的内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Food *food = [self.array objectAtIndex:indexPath.row];
    
    NSString *string = @"ss";
    
    MoreCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
        
        cell = [[[MoreCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:string]autorelease];
        
    }
    
    [cell.myImageView setImageWithURL:[NSURL URLWithString:food.pic_url] placeholderImage:[UIImage imageNamed:@""]];
    cell.name.text = food.userName;
    cell.instruction.text = food.desc;
    cell.instruction.alpha = 0.5;
    return cell;
    
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

// 点击cell执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //让cell点击以后回弹
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Food *food = [self.array objectAtIndex:indexPath.row];
    
      if ([food.userName isEqualToString:@"TOP25"] || [food.userName isEqualToString:@"最新美食"] || [food.userName isEqualToString:@"新人秀"]) {
        
//    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 3) {
    
        // 当点击cell的时候推出更多详情页面
        MoreDetailViewController *moreDetailVC = [[MoreDetailViewController alloc]init];
        moreDetailVC.food = [self.array objectAtIndex:indexPath.row];
        //    NSLog(@"头像图片的地址%@", moreDetailVC.food.userId);
        moreDetailVC.numberOfCell = indexPath.row;
        [self.navigationController pushViewController:moreDetailVC animated:YES];
        [moreDetailVC release];
        
      }
      else if ([food.userName isEqualToString:@"食单"]) {
          
          // 当点击食单cell的时候推出“全部食单”界面
          AllFoodMenuViewController *allFoodMenuVC = [[AllFoodMenuViewController alloc] init];
          allFoodMenuVC.address = food.objId;
          [self.navigationController pushViewController:allFoodMenuVC animated:YES];
          [allFoodMenuVC release];
//          ViewController *VC = [[ViewController alloc] init];
//          VC.str = food.url;
//          NSLog(@"网页的网址%@", VC.str);
//          [self.navigationController pushViewController:VC animated:YES];
//          [VC release];
          
          
      }
      else {
        
        // 当点击“活动”按钮的时候推出活动界面
        CrossSlipViewController *crossSlipVC = [[CrossSlipViewController alloc] init];
        Food *food = [self.array objectAtIndex:indexPath.row];
        crossSlipVC.address = food.objId;
//        NSLog(@"详情%@", food.objId);
        [self.navigationController pushViewController: crossSlipVC animated:YES];
        [crossSlipVC release];
    }
    
    
}

// 处理数据的方法
- (void)handleData
{
//    NSStsring *address = @"https://api.shiseapp.com/v2/discover/?_city=%E5%A4%A7%E8%BF%9E&_device=Matcha%20v2.5.0%20%28iPhone%206,%208.1.1%29&_version=2.5.0&conf_ver=1418604735&gps=38.882889,121.539660&uuid=b611c1feab43d2ee1585a574f539263f";
    NSString *address = @"https://api.shiseapp.com/v2/discover/?";
    [NetHandler getDataWithUrl:address completion:^(NSData *data) {
        
        NSError *error = nil;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
        
        NSArray *dataArray = [dic objectForKey:@"data"];
        
        for (int i = 0; i < dataArray.count; i ++) {
            
            NSDictionary *tempDic = [dataArray objectAtIndex:i];
            NSString *string = [tempDic objectForKey:@"title"];
//            NSLog(@"%@", string);
            if ([string isEqualToString:@"TOP25"] || [string isEqualToString:@"最新美食"] || [string isEqualToString:@"活动"] || [string isEqualToString:@"新人秀"] || [string isEqualToString:@"食单"] || [string isEqualToString:@"食色坊"] || [string isEqualToString:@"食色达人"]) {
                
                Food *food = [[Food alloc] initWithDictionary:tempDic];
//                NSLog(@"上来没%@", food.url);
                [self.array addObject:food];
                [food release];
            }
            
        }
        [self.tableView reloadData];
    }];
}

// 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    if ([self GetCurrntNet]) {
        //[self handleData];
//        [self handleData];
        
    }
    else {
        /// 缓冲
        //        NSLog(@"没有网络");
        self.noHUD = [[MBProgressHUD alloc]initWithView:self.view];
        [self.noHUD setMode:MBProgressHUDModeIndeterminate];
        self.noHUD.labelText = @"网络不可用,请检查";
        [self.noHUD show:YES];
        [self performSelector:@selector(removeNoHUDView) withObject:self afterDelay:2];
        [self.view addSubview:_noHUD];
        [_noHUD release];
    }
    //    [self.scrollView reloadData];
    
}

-(NSString*) GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            result=@"3g";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            result=@"wifi";
            break;
    }
    return result;
}

-(void)removeNoHUDView
{
    [self.noHUD removeFromSuperview];
}


- (void)dealloc
{
    [_array release];
    [_tableView release];
    [_noHUD release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
